package com.njmaomao.gj.pyot.service.domain;

import com.njmaomao.gj.pyot.common.Utils;
import com.njmaomao.gj.pyot.common.exception.ExternalSystemError;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;

@Slf4j
public class HttpService {

    @Autowired
    protected RestTemplate restTemplate;

    public <Req, Resp> Resp post(String url, Req request, ParameterizedTypeReference<Resp> responseType) {
        long start = System.currentTimeMillis();
        log.info("start post url: {}, req: {}", url, Utils.toJson(request));
        Resp response = null;
        try {
            response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    new org.springframework.http.HttpEntity<>(request, new HttpHeaders()),
                    responseType
            ).getBody();
        } catch (Exception e) {
            throw new ExternalSystemError(getInterfaceName(url) + " " + e.getMessage(), e);
        }
        log.info("end post spent: {} ms, resp: {}", System.currentTimeMillis() - start, Utils.toJson(response));
        return response;
    }

    private String getInterfaceName(String url) {
        String[] urlArray = url.split("/");
        String system = urlArray.length < 4 ? url : urlArray[3];
        return system;
    }

}
